package com.xxl.job.admin.core.util.alarm;

import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.admin.core.alarm.impl.DingdingJobAlarm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenlinqing
 * @description:
 * @date: 2025/8/25 11:25
 */
@Component
public class LarkAlarmUtil {
    private static Logger logger = LoggerFactory.getLogger(DingdingJobAlarm.class);
    private static ObjectMapper objectMapper = new ObjectMapper();

    public void sendMessage(String title, String alarmTo, String jobHandler, String jobDesc, String errorMsg) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("header", buildHeader(title));
            map.put("elements", buildElements(jobHandler, jobDesc, errorMsg));
            LarkMessage builder = new LarkMessage();
            builder.setMsgType("interactive");
            builder.setCard(map);
            HttpRequest post = HttpUtil.createPost(alarmTo);
            HttpRequest request = post.body(objectMapper.writeValueAsString(builder), ContentType.JSON.toString());
            HttpResponse execute = request.execute();
            logger.info("Lark send message result:{}", execute);
            if (!execute.isOk()) {
                throw new RuntimeException(execute.body());
            }
        } catch (Exception e) {
            logger.error("Lark send message error:{}", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    private List buildElements(String jobHandler, String jobDesc, String errorMsg) {
        Map<String, String> map = new HashMap<>();
        map.put("tag", "markdown");
        map.put("content", getAtText(jobHandler, jobDesc, errorMsg));
        return Collections.singletonList(map);
    }

    private Map<String, Object> buildHeader(final String title) {
        Map<String, Object> map = new HashMap<>();
        map.put("template", "red");

        Map<String, String> titleMap = new HashMap<>();
        titleMap.put("content", title);
        titleMap.put("tag", "plain_text");

        map.put("title", titleMap);
        return map;
    }

    public String getAtText(String jobHandler, String jobDesc, String errorMsg) {
        String text = "定时任务handler：%s，\n 定时任务描述：%s \n 执行报错。错误日志如下：\n %s".formatted(jobHandler, jobDesc, errorMsg);
        StringBuilder sb = new StringBuilder(text);
        return sb.toString();
    }

    private static class LarkMessage {

        @JsonProperty("msg_type")
        private String msgType;

        private Map<String, Object> card;

        public String getMsgType() {
            return msgType;
        }

        public void setMsgType(String msgType) {
            this.msgType = msgType;
        }

        public Map<String, Object> getCard() {
            return card;
        }

        public void setCard(Map<String, Object> card) {
            this.card = card;
        }
    }
}
